<template>
  <div style="padding: 0 15px;">

    <el-steps :active="2" simple style="margin-top: 20px">
      <el-step title="类目选择" icon="el-icon-receiving" />
      <el-step title="添加属性" icon="el-icon-s-operation" />
      <el-step title="添加图片" icon="el-icon-picture-outline" />
      <el-step title="添加详情" icon="el-icon-notebook-2" />
    </el-steps>

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              <i class="el-icon-edit" /> &nbsp; 图片管理
            </h3>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: right">
          <div class="grid-content bg-purple">
            <el-button
              size="small"
              type="primary"
              :disabled="albumCreated"
              icon="el-icon-circle-plus-outline"
              @click="addAlbumDialogVisible = true"
            >新建相册</el-button>
            <el-upload
              multiple
              style="display: inline-block; margin: 0px 10px"
              :action="UPLOAD_URL"
              name="image"
              :on-success="handleSuccess"
              :auto-upload="true"
              :show-file-list="false"
              :headers="tokenHeader"
            >
              <el-button
                size="small"
                type="primary"
                :disabled="!albumCreated"
                icon="el-icon-circle-plus-outline"
              >上传图片</el-button>
            </el-upload>
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
            >批量选择</el-button>
          </div>
        </el-col>
      </el-row>

      <div class="divider" />

      <div v-if="albumCreated">
        <div class="namerow">
          {{ ruleForm.albumInfo.name }}
        </div>
        <el-row class="descrow">
          {{ ruleForm.albumInfo.description }}
        </el-row>
        <el-row class="bzrow">
          <p>1. 单图图片尺寸为: 300*300,文件大小不得超过300k</p>
          <p>2. 商城前端最多展示10张图片</p>
        </el-row>
      </div>
    </div>

    <div class="box">
      <div v-if="albumCreated && pictures.length != 0">
        <photo-pic-item
          v-for="(item, i) in pictures"
          :key="item.id"
          :current-pic="item"
          :index="i + 1"
          :selected="item.selected"
          @coverChanged="handleCoverChanged"
          @picSelected="handlePicSelected"
          @picCancelSelected="handlePicCancelSelected"
          @picDeleted="handlePicDeleted"
        />

        <!-- <div class="pagination">
          <el-pagination
            background
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div> -->
      </div>
      <div v-else>
        <el-empty description="没有任何图片" />
      </div>
      <div class="divider" />
      <el-button @click="$router.go(-1)">上一步，添加属性</el-button>
      <el-button type="primary" @click="nextStep()">下一步，添加详情</el-button>
    </div>

    <!-- 新增相册 -->
    <el-dialog
      title="新建相册"
      :visible.sync="addAlbumDialogVisible"
      :modal-append-to-body="false"
    >
      <el-form :model="addForm">
        <el-form-item label="相册名称" label-width="120px">
          <el-input v-model="addForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="相册简介" label-width="120px">
          <el-input v-model="addForm.description" autocomplete="off" />
        </el-form-item>
        <el-form-item label="排序序号" label-width="120px">
          <el-input v-model="addForm.sort" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import photoPicItem from '@/components/album/PhotoPicItem.vue'
import LocalStorage from '@/utils/StorageUtils.js'
import * as albumApi from '@/api/album.js'
import { getToken } from '@/utils/auth.js'
export default {
  components: {
    photoPicItem
  },
  data() {
    return {
      UPLOAD_URL: `${process.env.VUE_APP_BASE_API}upload/product-image`,
      albumCreated: false, // 标识相册是否已经创建
      addAlbumDialogVisible: false, // 标识是否显示新建相册对话框
      addForm: {}, // 定义新建相册表单对象
      tokenHeader: { Authorization: getToken() }, // 定义请求头
      ruleForm: { // 定义新建SPU完成的表单数据
        name: '',
        typeNumber: '',
        title: '',
        discription: '',
        listPrice: 0.0,
        stock: 0,
        stockThreshold: 0,
        unit: '',
        brandId: 0,
        categoryId: 0,
        categoryName: '',
        albumId: 0,
        pictures: [],
        keywords: '',
        tags: '',
        sort: 10,
        detail: '',
        parentId: [0] // 默认父类别为根类别
      },
      pictures: [], // 定义当前相册中包含的所有图片
      // currentPage: 1, // 当前页
      // total: 0, // 总页数
      // pageSize: 100, // 每页条目数

      cuser: {},

      input: '',
      value: '',
      options: [
        {
          value: 'enable',
          label: '启用'
        },
        {
          value: 'disable',
          label: '禁用'
        }
      ]
    }
  },

  /** 页面挂在完毕后执行 */
  mounted() {
    // 读取LocalStorage，加载缓存数据
    this.ruleForm = LocalStorage.get(LocalStorage.KEY_ADD_SPU)
    if (this.ruleForm.albumId) {
      // 已经创建了相册
      this.albumCreated = true
      // 加载相册内容
      this.loadAlbumPictures()
    }
  },
  methods: {
    /** 加载图片列表 */
    loadAlbumPictures() {
      const albumId = this.ruleForm.albumId
      albumApi.getPictures(albumId).then((res) => {
        console.log('加载当前图片列表', res)
        this.pictures = res.data
      })
    },
    nextStep() {
      // 如果没有相册，没有任何图片就不能下一步
      if (!this.albumCreated || this.pictures.length === 0) {
        this.$message.error('必须先创建相册并上传至少一张图片！')
      } else {
        // 将相册中图片URL取出来使用逗号连接存储到ruleForm中的pictures属性中
        this.ruleForm.pictures = this.pictures.map((item) => item.url).join(',')
        // 重新存入LocalStorage
        LocalStorage.save(LocalStorage.KEY_ADD_SPU, this.ruleForm)
        console.log('下一步，添加详情', this.ruleForm)
        this.$router.push('/spu/step4')
      }
    },

    /** 当图片被取消选中时 */
    handlePicCancelSelected(picture) {
      console.log('取消选中', picture)
      // for (let i = 0; i < this.ruleForm.pictures.length; i++) {
      //   if (this.ruleForm.pictures[i] === picture.url) {
      //     this.ruleForm.pictures.splice(i, 1)
      //     break
      //   }
      // }
    },

    /** 当图片被选中时 */
    handlePicSelected(picture) {
      console.log('选中', picture)
      // // 向ruleForm.pictures中新增图片路径
      // if (this.ruleForm.pictures === undefined) {
      //   this.ruleForm.pictures = []
      // }
      // this.ruleForm.pictures.push(picture.url)
    },

    /** 处理更新封面后的业务 */
    handleCoverChanged(picture) {
      console.log('更新封面', picture)
      albumApi.setCover(picture.albumId, picture.id).then((res) => {
        console.log('更新封面成功', res)
        // 重新加载相册图片
        this.loadAlbumPictures()
      })
    },
    /** 处理删除图片后的业务 */
    handlePicDeleted(picture) {
      console.log('删除图片', picture)
      // 调用API，删除图片
      albumApi.deletePicture(picture.albumId, picture.id).then(response => {
        console.log('删除图片成功：', response)
        // 重新加载相册图片
        this.loadAlbumPictures()
        albumApi.deleteUpload(picture.url).then(response => {
          console.log('删除图片成功：', response)
        })
      })
    },

    /** 选择图片确定时，将图片存入FormData */
    handleSuccess(res) {
      // 上传成功后，将该图片添加到相册
      console.log('上传成功，并将图片绑定到相册：', res)
      // 完善图片对象，新增数据，将图片绑定到相册
      const pictureUrl = res.data
      const picture = {
        url: pictureUrl,
        albumId: this.ruleForm.albumId
      }
      // 调用API，将图片绑定到相册
      albumApi.addPicture(picture).then(response => {
        console.log('绑定图片到相册成功：', response)
        // 重新加载相册图片
        this.loadAlbumPictures()
        console.log('重新加载相册图片')
      })
    },
    /** 处理更新页码后的业务 */
    handleCurrentChange(val) {
      console.log(`即将加载选中页: 第${val}页`)
      this.currentPage = val
      this.loadAlbumPictures()
    },

    handleAvatarSuccess(res, file) {
      this.cuser.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    /** 提交新建相册 */
    submitAddForm() {
      console.log('提交新建相册', this.addForm)
      albumApi.createAlbum(this.addForm).then((res) => {
        console.log('新建相册：', res)
        this.ruleForm.albumInfo = this.addForm
        this.ruleForm.albumId = res.data
        LocalStorage.save(LocalStorage.KEY_ADD_SPU, this.ruleForm)
        this.$message({
          showClose: true,
          message: '创建相册成功',
          type: 'success'
        })
        this.addAlbumDialogVisible = false
        this.albumCreated = true
      })
    }
  }
}
</script>
<style scoped>
.namerow {
  font-weight: bold;
  font-size: 1.1em;
  color: #a33;
  margin-bottom: 20px;
}
.descrow {
  margin-bottom: 20px;
  color: #888;
}
.bzrow {
  columns: #666;
  font-size: 0.9em;
}
</style>
